/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package k3tool.common.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;

/**
 *
 * @author Jeff Huang
 */
public class Txt2XHtml {

    /**
     * Clean invalid xml characters
     * http://www.theplancollection.com/house-plan-related-articles/hexadecimal-value-invalid-character
     */
    public static String cleanInvalidXmlChars(String text) {
        
        String re = "[^^\u0009\r\n\u0020-\uD7FF\uE000-\uFFFD]";
        return text.replaceAll(re, " ");
    }

    public void filter(Reader input, OutputStream output, String encoding) throws IOException {
        Document doc = XHtmlConstants.createXHtmlDocument();
        Element htmlEl = doc.getRootElement();
        Element bodyEl = new Element("body");

        String line = null;
        BufferedReader br = new BufferedReader(input);
        while ((line = br.readLine()) != null) {
            Element pEl = new Element("p");
            pEl.appendChild(cleanInvalidXmlChars(line));
            bodyEl.appendChild(pEl);
        }

        htmlEl.appendChild(bodyEl);
        Serializer s = null;
        if (encoding == null) {
            s = new Serializer(output);
        } else {
            s = new Serializer(output, encoding);
        }
        s.setIndent(2);
        s.write(doc);
    }
}
